package com.ks.utils.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * @author Administrator
 * @version 2017年3月10日
 */
public class SUtilHttp {

	private static Logger logger = LoggerFactory.getLogger(SUtilHttp.class);

	private static final CloseableHttpClient httpClient;
	public static final String CHARSET = "UTF-8";
	// 采用静态代码块，初始化超时时间配置，再根据配置生成默认httpClient对象
	static {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	}

	/**
	 * 发起get请求  默认charset 为UTF-8
	 * @param url 请求地址
	 * @param queryParams URL参数
	 * @return
	 */
	public static String doGetRequest(String url, Map<String, Object> queryParams) {
		return doGetRequest(url, queryParams, CHARSET);
	}

	/**
	 * 发起post请求 默认charset 为 UTF-8 
	 * @param url 请求地址
	 * @param queryParams	跟随在URL后面的参数
	 * @param bodyParams	body 参数
	 * @return
	 * @throws Exception
	 */
	public static String doPostRequest(String url,Map<String, Object> queryParams,Map<String, Object> bodyParams) throws Exception {
		return doPostRequest(url, queryParams, bodyParams, CHARSET);
	}
	
	public static String doGetSSLRequest(String url, Map<String, Object> params) {
		return doGetSSL(url, params, CHARSET);
	}

	

	/**
	 * HTTP Get 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 */
	public static String doGetRequest(String url, Map<String, Object> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					String value = entry.getValue().toString();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				// 将请求参数和url进行拼接
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * HTTP put
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 */
	public static String doPutRequest(String url, Map<String, Object> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					String value = entry.getValue().toString();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				// 将请求参数和url进行拼接
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpPut httpPut = new HttpPut(url);
			CloseableHttpResponse response = httpClient.execute(httpPut);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPut.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * HTTP delete
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 */
	public static String doDeleteRequest(String url, Map<String, Object> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					String value = entry.getValue().toString();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				// 将请求参数和url进行拼接
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpDelete httpDelete = new HttpDelete(url);
			CloseableHttpResponse response = httpClient.execute(httpDelete);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpDelete.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * HTTP Post 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 * @throws IOException
	 */
	public static String doPostRequest(String url, Map<String, Object> queryParams,Map<String, Object> bodyParams, String charset) 
			throws Exception {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		if (queryParams != null && !queryParams.isEmpty()) {
			List<NameValuePair> pairs = new ArrayList<NameValuePair>(queryParams.size());
			for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
				String value = entry.getValue().toString();
				if (value != null) {
					pairs.add(new BasicNameValuePair(entry.getKey(), value));
				}
			}
			// 将请求参数和url进行拼接
			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
		}
		HttpPost httpPost = new HttpPost(url);
		
		httpPost.setHeader("Content-Type", "application/json");
		
		if (bodyParams == null ) {
			bodyParams = new HashMap<String, Object>();
		}
		StringEntity s = new StringEntity(JSON.toJSONString(bodyParams), "utf-8");
		s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		httpPost.setEntity(s);
		
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				response.close();
		}
		return null;
	}
	
	
	/**
	 * 作废 已被doPostRequest 取代
	 * HTTP Post 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 * @throws IOException
	 */
	@Deprecated 
	public static String doPostBody(String url, String bodyJson, String charset) 
			throws Exception {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		HttpPost httpPost = new HttpPost(url);
		
		httpPost.setHeader("Content-Type", "application/json");
		
		if (StringUtils.isNotBlank(bodyJson)) {
			StringEntity s = new StringEntity(bodyJson, "utf-8");
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			httpPost.setEntity(s);
		}
		
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				response.close();
		}
		return null;
	}

	/**
	 * HTTPS Get 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset  编码格式
	 * @return 页面内容
	 */
	public static String doGetSSL(String url, Map<String, Object> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					String value = entry.getValue().toString();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);

			// https  注意这里获取https内容，使用了忽略证书的方式，当然还有其他的方式来获取https内容
			CloseableHttpClient httpsClient = SUtilHttp.createSSLClientDefault();
			CloseableHttpResponse response = httpsClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 这里创建了忽略整数验证的CloseableHttpClient对象
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}

	/**
	 * 发起http get请求获取返回结果
	 * HttpURLConnection 方式
	 * @param requestUrl 参数直接拼接在后面
	 *            请求地址
	 * @return
	 */
	public static String httpGetRequest(String requestUrl) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();

		} catch (Exception e) {
			logger.error("地址请求失败[GET]：" + requestUrl);
		} finally {
			if (httpUrlConn != null)
				httpUrlConn.disconnect();
		}
		return buffer.toString();
	}

	/**
	 * 发起http post请求获取返回结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpPostRequest(String requestUrl, Map<String, Object> params) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(true);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("POST");

			// httpUrlConn.setRequestProperty("Content-Type",
			// "application/x-www-form-urlencoded");
			// httpUrlConn.setRequestProperty("Connection", "Keep-Alive");//
			// 维持长连接
			// httpUrlConn.setRequestProperty("Charset", "UTF-8");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");

			httpUrlConn.setConnectTimeout(1000);
			httpUrlConn.setReadTimeout(5 * 1000);
			DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
			if (params != null && !params.isEmpty()) {
				out.writeBytes(paramstourl(params));
			}
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
			logger.error("地址请求失败[POST]：" + requestUrl + ";参数：" + params);
		} finally {
			if (httpUrlConn != null)
				httpUrlConn.disconnect();
		}
		return buffer.toString();
	}

	/**
	 * 发起http post请求获取返回结果 自定义设置相关超时时间
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpPostRequest(String requestUrl, Map<String, Object> params,	Integer connectTimeout, Integer readTimeout) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(true);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("POST");
			if (connectTimeout != null) {
				httpUrlConn.setConnectTimeout(connectTimeout);
			}
			if (readTimeout != null) {
				httpUrlConn.setReadTimeout(readTimeout);
			}
			DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
			if (params != null && !params.isEmpty()) {
				out.writeBytes(paramstourl(params));
			}
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
			logger.error("地址请求失败[POST]：" + requestUrl + ";参数：" + params);
		} finally {
			if (httpUrlConn != null)
				httpUrlConn.disconnect();
		}
		return buffer.toString();
	}

	public static String paramstourl(Map<String, Object> params) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator(); it.hasNext();) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
			if (i > 0) {
				sb.append("&");
			}
			String value = "";
			try {
				value = URLEncoder.encode(entry.getValue().toString(), "UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
			sb.append(entry.getKey() + "=" + value);
			i++;
		}
		return sb.toString();
	}

}
